package com.jhws.sys.appUpgrade.controller;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;

import com.jhws.business.aliyun.service.OSSClientService;
import com.jhws.common.base.bo.JsonRespData;
import com.jhws.util.StringUtils;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.jhws.sys.appUpgrade.bo.TblSoftDimBo;
import com.jhws.sys.appUpgrade.bo.TblSoftLabelDimBo;
import com.jhws.util.GetId;
import com.jhws.core.db.BaseDao;
import com.jhws.sys.appUpgrade.service.ITblSoftDimService;
import com.jhws.sys.appUpgrade.service.ITblSoftLabelDimService;

import javax.annotation.Resource;

@Controller
@RequestMapping("/appupdate")
public class AppUpdateCtrl {

    @Resource
    protected ITblSoftDimService ISoftService;

    @Resource
    protected ITblSoftLabelDimService ISoftLabelService;
    @Resource
    private OSSClientService ossClientService;

    private BaseDao dao = new BaseDao();

    @RequestMapping("query.x")
    @ResponseBody
    public JsonRespData query(@RequestParam Map param) throws Exception {
        return new JsonRespData("", 1, ISoftService.findTblSoftDim(param));
    }

    /**
     * 更新状态
     * @param softCode
     * @param state
     * @return
     * @throws Exception
     */
    @RequestMapping("updateState.x")
    @ResponseBody
    public JsonRespData updateState(String softCode, String state) throws Exception {
        TblSoftDimBo softDimBo = ISoftService.findTblSoftDimById(softCode);
        softDimBo.setSoftState(state);
        ISoftService.save(softDimBo);
        return new JsonRespData("", 1, "");
    }

    @RequestMapping("remove.x")
    @ResponseBody
    public JsonRespData removeTblSoftDim(String softCode) throws Exception {
        this.ISoftService.removeSoftDim(softCode);
        return new JsonRespData("", 1, "");
    }

    @RequestMapping("saveTblSoftDim.x")
    @ResponseBody
    public JsonRespData saveTblSoftDim(String fileName, String filePath, TblSoftDimBo bo) throws java.lang.Exception {
        TblSoftLabelDimBo tblSoftLabelDimBo = ISoftLabelService.findTblSoftLabelDimById(bo.getSoftLabelCode());
        StringBuilder updatePath = new StringBuilder();
        updatePath.append("appupdate/");
        // 判断代码版本号，版本号大小
        TblSoftDimBo tblSoftDimBoMax = dao.j().queryForObject(
                "select * from tbl_soft_dim where code_vision =(select max(cast(code_vision as UNSIGNED INTEGER)) from tbl_soft_dim where equ_type= ? and soft_label = ? ) and equ_type= ? and soft_label = ? ",
                new Object[]{bo.getEquType(), tblSoftLabelDimBo.getSoftLabe(), bo.getEquType(), tblSoftLabelDimBo.getSoftLabe()}, new PersonRowMapper());

        if (tblSoftDimBoMax != null
                && compareVersion(tblSoftDimBoMax.getSoftVision(), bo.getSoftVision()) >= 0) {
            return new JsonRespData("", -1, "版本号不能低于或等于上一个版本");
        }

        if (tblSoftDimBoMax != null
                && Integer.parseInt(bo.getCodeVision()) <= Integer.parseInt(tblSoftDimBoMax.getCodeVision())) {
            return new JsonRespData("", -1, "代码版本号不能低于或等于上一个版本");
        }

        switch (bo.getEquType()) {
            case "p":
                updatePath.append("pad/");
                break;
            case "d":
                updatePath.append("outdoor/");
                break;
            case "m":
                updatePath.append("mobile/");
                break;
        }

        if (StringUtils.isNotEmpty(filePath)) {
            updatePath.append(tblSoftLabelDimBo.getSoftLabe())
                    .append("/")
                    .append(bo.getSoftVision())
                    .append("/");
            if (StringUtils.isNotEmpty(fileName)) {
                updatePath.append(fileName);
            } else {
                updatePath.append(bo.getSoftVision())
                        .append(".apk");
            }
            ossClientService.gerneralCopyFile(filePath, updatePath.toString());
        }

        bo.setSoftCode(GetId.randomID());
        bo.setSoftLabel(tblSoftLabelDimBo.getSoftLabe());
        bo.setSoftLabeName(tblSoftLabelDimBo.getSoftLabeName());
        bo.setSoftState("1");
        ISoftService.save(bo);
        return new JsonRespData("", 1, "添加软件信息成功");
    }


    @SuppressWarnings("Duplicates")
    class PersonRowMapper implements RowMapper<TblSoftDimBo> {
        public TblSoftDimBo mapRow(ResultSet rs, int value) throws SQLException {
            TblSoftDimBo tblSoftDimBo = new TblSoftDimBo();
            tblSoftDimBo.setCodeVision(rs.getString("code_vision"));
            tblSoftDimBo.setEquType(rs.getString("equ_type"));
            tblSoftDimBo.setMandatoryUpgrade(rs.getString("mandatory_upgrade"));
            tblSoftDimBo.setSoftCode(rs.getString("soft_code"));
            tblSoftDimBo.setSoftFn(rs.getString("soft_file_name"));
            tblSoftDimBo.setSoftName(rs.getString("soft_name"));
            tblSoftDimBo.setSoftSize(rs.getString("soft_size"));
            tblSoftDimBo.setSoftState(rs.getString("soft_state"));
            tblSoftDimBo.setSoftVision(rs.getString("soft_vision"));
            tblSoftDimBo.setUpdExp(rs.getString("upd_exp"));
            return tblSoftDimBo;
        }
    }

    /**
     * 比较版本号的大小,前者大则返回一个正数,后者大返回一个负数,相等则返回0
     *
     * @param version1
     * @param version2
     * @return
     */
    @SuppressWarnings("Duplicates")
    private int compareVersion(String version1, String version2) throws Exception {
        if (version1 == null || version2 == null) {
            throw new Exception("compareVersion error:illegal params.");
        }
        String[] versionArray1 = version1.split("\\.");// 注意此处为正则匹配，不能用"."；
        String[] versionArray2 = version2.split("\\.");
        int idx = 0;
        int minLength = Math.min(versionArray1.length, versionArray2.length);// 取最小长度值
        int diff = 0;
        while (idx < minLength && (diff = versionArray1[idx].length() - versionArray2[idx].length()) == 0// 先比较长度
                && (diff = versionArray1[idx].compareTo(versionArray2[idx])) == 0) {// 再比较字符
            ++idx;
        }
        // 如果已经分出大小，则直接返回，如果未分出大小，则再比较位数，有子版本的为大；
        diff = (diff != 0) ? diff : versionArray1.length - versionArray2.length;
        return diff;
    }
}
